const fs = require("fs");
const path1 = require("path");
const prettier = require("prettier");
const createLogger = require("terminal-progress-estimator");
// const { OpenAI  } = require("openai");
// const { HttpsProxyAgent } = require('https-proxy-agent');
const axios = require('axios');  // 引入 axios 来进行调试

// 读取 business 文件夹下的所有文件
function readDirFiles(path) {
  const fileContents = [];
  fs.readdirSync(path).forEach((file) => {
    const filePath = path1.resolve(__dirname, path, file);
    const content = fs.readFileSync(filePath, "utf-8");
    fileContents.push({
      name: file,
      content,
    });
  });

  return fileContents;
}

// 调用 OpenAI 的 API 进行代码审查
async function getChatGPTCompletion(text) {
  const apiKey =
    "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";

  // 配置代理
  const proxy = 'http://127.0.0.1:7897'; // 代理服务器地址
  const agent = new HttpsProxyAgent(proxy); // 创建代理对象

  // 配置 OpenAI 客户端，指定代理设置
  const openai = new OpenAI({
    apiKey: apiKey,
    httpsAgent: agent,
    // 忽略 SSL 证书错误
    https: {
      rejectUnauthorized: false,
    }
  });

  try {
    // 调用 OpenAI API 进行代码审查
    const completion = await openai.chat.completions.create({
      model: "gpt-3.5-turbo",
      messages: [
        {
          role: "user",
          content: `查找以下代码的问题，修复它们并解释错误所在, 给出修改后的代码：\n\n${text}`,
        },
      ],
    });

    return completion;
  } catch (error) {
    console.error('API Connection Error:', error.message);
    console.error('Full Error Details:', error);

    // 使用 axios 直接测试代理连接
    try {
      const response = await axios.get('https://api.openai.com/v1/models', {
        headers: { 'Authorization': `Bearer ${apiKey}` },
        httpsAgent: agent, // 使用相同的代理配置
        // 忽略 SSL 证书错误
        https: {
          rejectUnauthorized: false,
        }
      });
      console.log('API test success:', response.data);
    } catch (axiosError) {
      console.error('Axios Test Error:', axiosError.message);
      console.error('Axios Full Error:', axiosError);
    }
  }
}

async function getDeepseek(text) {
  const apiKey = 'sk-f1dba6c2c8aa4cb992193d95bb96be58'
  try {
    const completion = await axios.post('http://10.200.205.59:11434/api/generate', {
      "model": "deepseek-r1:8b",
      "prompt": `查找以下代码的问题，修复它们并解释错误所在, 给出修改后的代码：\n\n${text}`,
      "stream": false
    },
      {
        headers: { 'Authorization': `Bearer ${apiKey}` },
      });
    return completion.data;
  } catch (axiosError) {
    console.error('Axios测试错误:', axiosError.message);
    console.error('Axios完整错误:', axiosError);
  }
}

const logger = createLogger();

// 显示加载进度
async function loading(label, options) {
  let resolve = () => { };
  const promise = new Promise((rsl) => {
    resolve = rsl;
  });
  logger(promise, label, options);
  return resolve;
}

// 处理每个文件的代码审查
async function asyncFunction(file) {
  return new Promise(async (resolve, reject) => {
    try {
      // 调用deepseek进行代码审查
      const completion = await getDeepseek(file.content);
      console.log(completion);

      // 获取审查结果
      const message = completion.response;

      // 判断文件类型
      const isSql = file.name.includes(".sql");
      const prefix = isSql ? "--" : "//";

      // 格式化内容，注释掉审查的内容
      const content = message.replace(/^[\u4e00-\u9fa51-9]/gm, function (str) {
        return `${prefix}${str}`;
      });

      // 写入审查后的文件
      fs.writeFileSync(
        `./codeReview/${file.name}`,
        `${prefix} 源代码\n${file.content}\n${content}`
      );

      resolve();
    } catch (error) {
      reject(error);
    }
  });
}

// 主函数
async function main(path) {
  const resolve = await loading(`开始使用deepseek检查代码...`);
  const files = readDirFiles(path);
  const promises = [];

  // 遍历文件，处理每个文件
  files.forEach(async (file) => {
    promises.push(asyncFunction(file));
  });

  // 等待所有文件处理完成
  await Promise.all(promises);
  resolve(`codeReview文件夹下已生成代码检查结果`);

}

// 启动主函数
main("./business");


